
package com.vanda.db;
import java.util.HashMap;
import java.util.Iterator;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vanda.db.cfg.ConfigBean;
import com.vanda.db.cfg.Environment;
import com.vanda.util.LogFunc;

/**
 * Hibernate工具类 <br>
 * 
 * @author 王瑛<br>
 * @version Version 1.00<br>
 */
public class HibernateUtil {
	/** 取得日志类 */
	private static Log log = LogFactory.getLog(HibernateUtil.class);
	/** 保存Hibernate SessionFactory实例 */
	private static HashMap _hmFactory = new HashMap(5);

	static {
		initHibernate();
	}
	/**
	 * 初始化hibernate环境，取得SessionFactory实例
	 * @return
	 */
	public static boolean initHibernate() {
		boolean b = true;
		try {
			HashMap hmHiber = ConfigBean.getHibernate();
			Iterator iter = hmHiber.keySet().iterator();
			while (iter.hasNext()) {
				String key = (String) iter.next();
				String path = (String) hmHiber.get(key);
				SessionFactory sessionFactory = createFactory(path);
				_hmFactory.put(key, sessionFactory);
			}
		} catch (Exception ex) {
			b = false;
			LogFunc.info(ex);
		}
		return b;
	}
	
	/**
	 * 创建SessionFactory类
	 * @param path Hibernate配置文件路径
	 * @return 
	 * @throws Exception
	 */
	private static SessionFactory createFactory(String path) throws Exception {
		Configuration config = new Configuration().configure(path);
		SessionFactory factory = config.buildSessionFactory();
		return factory;
	}
	//private static final ThreadLocal threadLocal = new ThreadLocal();
	/**
	 * 取得当前线程的session实例
	 * @return hibernate session
	 * @throws HibernateException
	 */
	static Session currentSession() throws HibernateException {
		return currentSession(Environment.HIBERNATE_DEFAULT);
	}
	
	/**
	 * 取得指定数据源的Session实例
	 * @param type
	 * @return
	 * @throws HibernateException
	 */
	static Session currentSession(String type) throws HibernateException {
		SessionFactory sessionFactory = (SessionFactory) _hmFactory.get(type);
		Session s = sessionFactory.openSession();

		return s;
	}
	
	/**
	 * 关闭session
	 * @throws HibernateException
	 */
	static void closeSession(Session s) throws HibernateException {
		try {
			if (s != null) {
				s.close();
			}
		} catch (HibernateException e) {
			throw e;
		}
	}
}
